#!/usr/bin/env python3
# encoding: utf-8

"""
@version: 1.0
@author: 周永波
@file: ret.py
@time: 2020/8/11 9:50
"""
# import json
import traceback
from typing import Tuple
from flask import Blueprint, json


class ResultInfo:

    def __init__(self, code: int, message: str, data={}) -> None:
        self.code = code
        self.message = message
        self.data = data

    def dict_serialize(self):
        if self.data is not None:
            self.data = self.data.__dict__
        return self.__dict__

    @staticmethod
    def success(data=None):
        return ResultInfo(100, "", data)

    @staticmethod
    def error(code: int, message: str):
        return ResultInfo(code, message)

    @staticmethod
    def error_500(message: str):
        return ResultInfo(500, message)


# 重写蓝图路由方法,实现restful统一数据格式返回
class views_rest(Blueprint):

    def route(self, rule, **options):
        def decorator(f):
            fn = restful(f)
            endpoint = options.pop("endpoint", f.__name__)
            self.add_url_rule(rule, endpoint, fn, **options)

            return fn
        return decorator


def restful(func):
    def wrapper():
        response = None
        ret = None
        try:
            response = func()
            if type(response) is Tuple:
                if len(response) == 1:
                    if type(response[0]) is not int:
                        ret = ResultInfo.success(response[0])
                    else:
                        ret = ResultInfo(response[0], response[1], None)
                elif len(response) == 2:
                    ret = ResultInfo(response[0], response[1], None)
                else:
                    ret = ResultInfo(response[0], response[1], response[2])
            else:
                ret = ResultInfo(100, None, response)
        except Exception as e:
            traceback.print_exc()
            ret = ResultInfo.error_500(str(e))
            pass
        return json.dumps(ret.__dict__)

    return wrapper
